import React, { useState, useEffect, useRef } from 'react';
import { Button, Dropdown, Space } from 'antd';
import { FixedSizeList as List } from 'react-window';
import { useParams } from 'react-router-dom';
import '../../style/main.css';
import '../../style/kuangjia.css';
import { useGlobalContext } from '../GlobalContext';
import SongListlist from './songListlist';

const Playlist = () => {
  const ulRef = useRef(null)
  const {
    userId, setUserId,
    favsongrefresh,
    setFavsongRefresh,
    playerlistfresh, setPlayerlistRefresh,
    currentIndex, setCurrentIndex,
    favsongListrefresh, setFavSonglistRefresh,
    playingDatalength, setPlayingDatalength, } = useGlobalContext();
  const { playlistId } = useParams();
  const [playlistData, setPlaylistData] = useState({});
  const [songLists, setSongLists] = useState({ songs: [] });
  const [userData, setUserData] = useState({ nickname: '', avatarUrl: '' });
  const [loading, setLoading] = useState(true);
  const [songListlistvisible, setSongListlistvisible] = useState(false)

  console.log('正在搜索Playlist ID:', playlistId);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const playlistResponse = await fetch(`http://localhost:3000/playlist/detail?id=${playlistId}`);
        const playlistData = await playlistResponse.json();
        const isFavorited = await checkFavorListStatus();
        setPlaylistData({
          ...playlistData.playlist,
          isFavorited,
        });

        const userResponse = await fetch(`http://localhost:3000/user/detail?uid=${playlistData.playlist.userId}`);
        const userData = await userResponse.json();
        setUserData({
          nickname: userData.profile.nickname,
          avatarUrl: userData.profile.avatarUrl,
        });
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [playlistId]);

  useEffect(() => {
    fetch(`http://localhost:3000/playlist/track/all?id=${playlistId}&limit=100&offset=1`)
      .then((response) => response.json())
      .then((data) => {
        setSongLists(data);
      })
      .catch((error) => {
        console.error('Error fetching song data:', error);
      });
  }, [playlistId]);

  const formatDuration = (duration) => {
    const minutes = Math.floor(duration / 60000);
    const seconds = ((duration % 60000) / 1000).toFixed(0);
    return (minutes < 10 ? '0' : '') + minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
  };

  const getPlayUrl = (id) => {
    return fetch(`http://localhost:3000/song/url?id=${id}`)
      .then((response) => response.json())
      .then((data) => data.data[0]?.url || '')
      .catch((error) => {
        console.error('Error fetching song URL:', error);
        return '';
      });
  };

  const [songData, setSongData] = useState([]);
  useEffect(() => {
    if (songLists.songs.length > 0) {
      const fetchSongData = async () => {
        const data = await Promise.all(
          songLists.songs.map(async (song, index) => {
            const playUrl = await getPlayUrl(song.id);
            const isFavorited = await checkFavorStatus(song.id);
            return {
              musicId: song.id,
              musicName: song.name,
              artName: song.ar[0]?.name || '未知',
              album: song.al.name,
              coverUrl: song.al.picUrl,
              lyricUrl: `http://localhost:3000/lyric?id=${song.id}`,
              dt: song.dt, // Convert to seconds
              playUrl,
              liked: isFavorited,
              songIndex: index,
              userId,
            };
          })
        );
        setSongData(data);
      };
      fetchSongData();
    }
  }, [songLists]);

  const checkFavorListStatus = async () => {
    try {
      const response = await fetch(`http://localhost:8088/favlist/${playlistId}`);
      const data = await response.json();
      if (data.code === 200 && data.data !== null) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      console.error("Error checking favor status: ", error);
      return false; // 默认未收藏
    }
  };

  const checkFavorStatus = async (songId) => {
    try {
      const response = await fetch(`http://localhost:8088/favor/${songId}`);
      const data = await response.json();
      if (data.code === 200 && data.data !== null) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      console.error("Error checking favor status: ", error);
      return false; // 默认未收藏
    }
  };

  const handleLikeClick = async (songId) => {
    const song = songData.find((s) => s.musicId === songId);
    const newLikedStatus = !song.liked;
    // 更新状态
    setSongData((prevSongs) =>
      prevSongs.map((s) =>
        s.musicId === songId ? { ...s, liked: newLikedStatus } : s
      )
    );
    const songPost = {
      musicId: song.musicId,
      musicName: song.musicName,
      artName: song.artName,
      album: song.album,
      coverUrl: song.coverUrl,
      playUrl: song.playUrl,
      lyricUrl: `http://localhost:3000/lyric?id=${song.musicId}`,
      dt: song.dt,
      liked: newLikedStatus,
      userId,
    };
    try {
      if (newLikedStatus) {
        // 收藏操作 (POST 请求)
        const response = await fetch("http://localhost:8088/favor", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(songPost),
        });

        if (!response.ok) {
          throw new Error("Failed to update favor status");
        }
        setFavsongRefresh(!favsongrefresh)
        console.log("Successfully added song to favorites:", songId);
      } else {
        // 取消收藏操作 (DELETE 请求)
        const response = await fetch(`http://localhost:8088/favor/${songId}`, {
          method: "DELETE",
        });

        if (!response.ok) {
          throw new Error("Failed to remove song from favorites");
        }
        setFavsongRefresh(!favsongrefresh)

        console.log("Successfully removed song from favorites:", songId);
      }
    } catch (error) {
      console.error("Error handling favor request: ", error);
    }
  };

  const handleListLikeClick = async () => {
    const newLikedStatus = !playlistData.isFavorited; // 切换收藏状态
    const songlistPost = {
      songListId: playlistId,
      songListName: playlistData.name,
      userId: userId,
      description: playlistData.description,
      coverUrl: playlistData.coverImgUrl,
      liked: newLikedStatus, // 确保最新状态
    };

    try {
      const response = await fetch(newLikedStatus ? "http://localhost:8088/favlist" : `http://localhost:8088/favlist/${playlistId}`, {
        method: newLikedStatus ? "POST" : "DELETE",
        headers: {
          "Content-Type": "application/json",
        },
        body: newLikedStatus ? JSON.stringify(songlistPost) : null,
      });

      if (!response.ok) {
        throw new Error("Failed to add to favorites");
      }

      // 更新本地收藏状态
      setPlaylistData((prevData) => ({
        ...prevData,
        isFavorited: newLikedStatus,
      }));
      setFavSonglistRefresh(!favsongListrefresh)
      console.log("Successfully added song to favorites:", playlistId);
    } catch (error) {
      console.error("Error handling favor request:", error);
    }
  };



  const handlePlayclick = async () => {
    try {
      // 检查数据库是否存在数据
      const checkResponse = await fetch("http://localhost:8088/playing", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });
      const playingData = await checkResponse.json();
      if (playingData.data.length > 0) {
        // 如果存在数据，先清空播放列表
        await handleDeleteAll();
      }

      // 添加当前歌单到播放列表
      const response = await fetch("http://localhost:8088/playing/all", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(songData),
      });
      if (!response.ok) {
        throw new Error("Failed to update playing list");
      }

      // 设置全局变量和刷新状态
      setCurrentIndex(0);
      setPlayerlistRefresh(!playerlistfresh);
      console.log("Successfully added songs to the playing list");
    } catch (error) {
      console.error("Error handling song list update: ", error);
    }
  };


  const handleDeleteAll = async () => {
    try {
      const response = await fetch('http://localhost:8088/playing/deleteall', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
      });

      if (!response.ok) {
        throw new Error('Failed to delete all songs');
      }
      // setPlayerlistRefresh(!playerlistfresh);

    } catch (error) {
      console.error('Error deleting all songs:', error);
    }
    // setCurrentIndex(0)
  };

  const handleSongPlayClick = async (index) => {
    try {
      // 检查数据库是否存在数据
      const checkResponse = await fetch("http://localhost:8088/playing", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });
      const playingData = await checkResponse.json();
      if (playingData.data.length > 0) {
        // 如果存在数据，先清空播放列表
        await handleDeleteAll();
      }

      // 添加当前歌单到播放列表
      const response = await fetch("http://localhost:8088/playing/all", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(songData),
      });
      if (!response.ok) {
        throw new Error("Failed to update playing list");
      }

      // 设置全局变量和刷新状态
      setCurrentIndex(index);
      setPlayerlistRefresh(!playerlistfresh);
      console.log("Successfully added songs to the playing list");
    } catch (error) {
      console.error("Error handling song list update: ", error);
    }
  };

  //测试窗口开关
  const [songsend, setSongsend] = useState({})
  const handleopenclick = (songId) => {
    setSongListlistvisible(true);
    const song = songData.find((s) => s.musicId === songId);
    setSongsend({
      musicId: song.musicId,
      musicName: song.musicName,
      artName: song.artName,
      album: song.album,
      coverUrl: song.coverUrl,
      playUrl: song.playUrl,
      lyricUrl: `http://localhost:3000/lyric?id=${song.musicId}`,
      dt: song.dt,
      liked: song.liked,
      userId,
    })
  }
  const handlesongListlisVisible = (visible) => {
    setSongListlistvisible(visible);
  }

  const handeladdSongTolist = async (songId) => {
    const song = songData.find((s) => s.musicId === songId);
    const songPost = {
      musicId: song.musicId,
      musicName: song.musicName,
      artName: song.artName,
      album: song.album,
      coverUrl: song.coverUrl,
      playUrl: song.playUrl,
      lyricUrl: `http://localhost:3000/lyric?id=${song.musicId}`,
      dt: song.dt,
      liked: song.liked,
      songIndex: playingDatalength + 1
    };
    try {
      const response = await fetch("http://localhost:8088/playing", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(songPost),
      });

      if (!response.ok) {
        throw new Error("Failed to update favor status");
      }
      setPlayerlistRefresh(!playerlistfresh)
    } catch (error) {
      console.error("Error handling favor request: ", error);
    }
  }

  const items = (songId) => [
    {
      key: '1',
      label: (
        <a
          href="#"
          onClick={(e) => {
            e.preventDefault(); // 阻止默认行为
            const song = songData.find((s) => s.musicId === songId); // 获取当前歌曲
            if (song.liked) {
              alert("歌曲已收藏");
            } else {
              handleLikeClick(song.musicId); // 执行收藏/取消收藏操作
            }
          }}
        >
          收藏
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
          下载
        </a>
      ),
    },
    {
      key: '3',
      label: (
        <a onClick={() => { handleopenclick(songId) }}>
          添加到歌单
        </a>
      ),
    },
    {
      key: '4',
      label: (
        <a onClick={() => handeladdSongTolist(songId)}>
          添加到播放
        </a>
      ),
    },
  ];
  // const renderRow = ({ index, style }) => {
  //   const item = songData[index];
  //   return (

  //   )
  // }

  return (
    <div className="page">
      {loading ? (
        <div className="loadingPage">
          <div className="loadcomponents">
            <div className='loader2'></div>
            <div className='loader1'></div>
          </div>
        </div>
      ) : (
        <div className="playlistcontainer">
          <div className="playlistinformation">
            <div className="playlistImg">
              <img src={playlistData.coverImgUrl} alt="" />
            </div>
            <div className="list-maininformation">
              <div id="playlistname">{playlistData.name}</div>
              <div className="playlistavatar">
                <img src={userData.avatarUrl} alt="" />
                <span id="playlistusernickname">{userData.nickname}</span>
              </div>
              <div className="introduce">{playlistData.description}</div>
              <div className="playlistControl">
                <button onClick={handlePlayclick}><i className="ri-play-fill"></i> 播放</button>
                <button><i className="ri-download-fill"></i> 下载</button>
                <button onClick={handleListLikeClick}><i className={playlistData.isFavorited ? "ri-heart-3-fill" : "ri-heart-3-line"}></i> 收藏</button>
                <button><i className="ri-share-fill"></i> 分享</button>
              </div>
            </div>
          </div>
          <div className="playlistnav">
            <ul>
              <li>歌曲</li>
              <li>评论</li>
            </ul>
          </div>
          <div className="search_songlist">
            <div className="serch_nav">
              <div>歌名/歌手</div>
              <div className="serch_nav_right">
                <div>专辑</div>
                <div>时长</div>
              </div>
            </div>
            <ul ref={ulRef}>
              {/* <List
                height={ulRef.current ? ulRef.current.clientHeight : 0}
                itemCount={songData.length}
                itemSize={50}
                width="100%"
              >
                {renderRow}
              </List> */}
              {songData.map((item, index) => {
                return (
                  <li
                    key={index}
                    onDoubleClick={() => handleSongPlayClick(index)}
                    className={currentIndex === index ? "playing" : ""}
                  >
                    <div className="hideicon">
                      <i className="ri-play-fill"></i>
                    </div>
                    <div className="search_songlist_left">
                      <div className="song_information">
                        <img
                          src={item.coverUrl}
                          alt={item.musicName}
                        />
                        <div className="song_name">
                          <span id="songname">{item.musicName}</span>
                          <span id="singer">{item.artName}</span>
                        </div>
                      </div>
                      <div className="dowhat">
                        <i
                          className={item.liked ? "ri-heart-3-fill" : "ri-heart-3-line"}// 根据每首歌的状态切换图标
                          onClick={(e) => {
                            e.stopPropagation();
                            handleLikeClick(item.musicId);
                          }}
                        ></i>
                        <div className='menu'>
                          <Space direction="vertical">
                            <Space wrap>
                              <Dropdown
                                menu={{
                                  items: items(item.musicId), // 动态传入当前歌曲的 ID
                                }}
                                placement="topLeft"
                                trigger={['click']}
                              >
                                <i className="ri-menu-4-line"></i>
                              </Dropdown>
                            </Space>
                          </Space>
                        </div>
                      </div>
                    </div>
                    <div className="search_songlist_right">
                      <div id="songalbum">{item.album}</div>
                      <div id="songduration">{formatDuration(item.dt)}</div>
                    </div>
                  </li>
                )
              })}
            </ul>
          </div>

        </div>
      )}
      {songListlistvisible && <SongListlist onviblechange={handlesongListlisVisible} songsend={songsend} />}
    </div>
  );
};

export default Playlist;
